<?php
// 完整处理流程：获取未处理菜品 -> 调用AI -> 更新数据库

require_once '../thinkphp/base.php';

use think\Db;

/**
 * 获取未处理的菜品（ai_called = 0）
 */
function getUnprocessedDishes($limit = 10) {
    return Db::name('food_dish')
        ->where('ai_called', 0)
        ->field('id, name')
        ->limit($limit)
        ->select();
}

/**
 * 调用API获取菜品信息
 */
function getDishInfoFromAPI($dishIds) {
    $url = 'http://localhost/api/food_ingredient/batchGetDishInfo';
    $data = ['dish_ids' => $dishIds];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/x-www-form-urlencoded'
    ]);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    return json_decode($response, true);
}

/**
 * 更新菜品信息和食材关联
 */
function updateDishInfoFromAI($dishData) {
    $successCount = 0;
    
    foreach ($dishData as $dishId => $dishInfo) {
        // 开始事务
        Db::startTrans();
        try {
            // 更新菜品信息
            $updateData = [
                'steps' => $dishInfo['steps'] ?? '',
                'cook_time' => $dishInfo['cook_time'] ?? '',
                'updatetime' => time()
            ];
            
            Db::name('food_dish')->where('id', $dishId)->update($updateData);
            
            // 删除原有的食材关联
            Db::name('food_ingredientrel')->where('dish_id', $dishId)->delete();
            
            // 添加新的食材关联
            if (!empty($dishInfo['ingredients'])) {
                $insertData = [];
                foreach ($dishInfo['ingredients'] as $index => $ingredient) {
                    // 只处理有效的食材（有ID的）
                    if (isset($ingredient['id']) && $ingredient['id'] > 0) {
                        $insertData[] = [
                            'dish_id' => $dishId,
                            'ingredient_id' => intval($ingredient['id']),
                            'quantity' => $ingredient['quantity'] ?? '100g',
                            'createtime' => time(),
                            'weigh' => $index + 1
                        ];
                    }
                }
                
                if (!empty($insertData)) {
                    Db::name('food_ingredientrel')->insertAll($insertData);
                    echo "为菜品ID {$dishId} 添加了 " . count($insertData) . " 个食材关联\n";
                }
            }
            
            // 标记为已调用AI
            Db::name('food_dish')->where('id', $dishId)->update(['ai_called' => 1]);
            
            // 提交事务
            Db::commit();
            echo "成功更新菜品ID {$dishId} 的信息\n";
            $successCount++;
            
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            echo "更新菜品ID {$dishId} 失败: " . $e->getMessage() . "\n";
        }
    }
    
    return $successCount;
}

/**
 * 主处理函数
 */
function processDishes() {
    echo "开始处理菜品信息...\n";
    
    // 获取未处理的菜品
    $dishes = getUnprocessedDishes(10);
    if (empty($dishes)) {
        echo "没有需要处理的菜品\n";
        return;
    }
    
    echo "找到 " . count($dishes) . " 个需要处理的菜品\n";
    
    // 提取菜品ID
    $dishIds = [];
    foreach ($dishes as $dish) {
        $dishIds[] = $dish['id'];
    }
    
    // 调用API获取菜品信息
    echo "调用API获取菜品信息...\n";
    $response = getDishInfoFromAPI($dishIds);
    
    if (empty($response) || $response['code'] != 1) {
        echo "获取菜品信息失败: " . ($response['msg'] ?? '未知错误') . "\n";
        return;
    }
    
    echo "成功获取菜品信息，开始更新数据库...\n";
    
    // 更新数据库
    $successCount = updateDishInfoFromAI($response['data']);
    
    echo "处理完成，成功更新 {$successCount} 个菜品\n";
}

// 执行处理
processDishes();
?>